package com.example.clipboardchecker;

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ToggleButton;

public class ClipboardCheckerActivity extends Activity {
	
	Activity ac = this;
	protected ClipboardManager cm;
	public final static String INFO_TAG = "clip123";
	public final static int ID = 12345;
	private Intent service_intent;
	private NfcAdapter nfc;
	private EditText message_edit;
	
	//GUI
	private ToggleButton togBut;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clipboard_checker);
		
		togBut = (ToggleButton) findViewById(R.id.toggleButton_clip_service);
		message_edit = (EditText) findViewById(R.id.editText_message);
		
		nfc = NfcAdapter.getDefaultAdapter(getApplicationContext());
		
		togBut.setChecked((ClipListenService.isRunning()));
		
		service_intent = new Intent(this,ClipListenService.class);
		
		cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
			processIntent(getIntent());
		}
		
		if (getIntent().getAction().equals("notif")) {
		
			String message = cm.getText().toString();
			
			message_edit.setText(message);
			
		}
	}
	
	public void processIntent(Intent intent){
		
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		
		NdefMessage nmsg = (NdefMessage) rawMsgs[0];
		
		message_edit.setText(new String(nmsg.getRecords()[0].getPayload()));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.clipboard_checker, menu);
		return true;
	}
	
	public void sendNFC(View view){
		////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/////NFC/
		
		String message = cm.getText().toString();
		
		NdefRecord nrec = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], message.getBytes());
		NdefMessage nfcMsg = new NdefMessage(nrec);
		
		nfc.setNdefPushMessage(nfcMsg, this);
	}
	
	public void onToggleClicked(View view){
		if (togBut.isChecked()){
			startService(service_intent);
		} else {
			stopService(service_intent);
		}
		
		
	}
}
